package com.tp.client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

import com.tp.cache.DomainCache;
import com.tp.helper.ClientDnsHelper;

/**
 * Cliente DNS Se encarga de hacer los pedidos de los dominios al servidor y
 * procesar su respuesta.
 */
public class Client {

	private static final boolean AUTO_FLUSH = true;
	private static String host = "127.0.0.1";
	private static int port = 8085;

	public static void main(String[] args) throws IOException,
			UnknownHostException {

		Socket echoSocket = null;
		PrintWriter out = null;
		BufferedReader in = null;
		BufferedReader stdIn = new BufferedReader(new InputStreamReader(
				System.in));
		String userInput = "";
		ClientDnsHelper clientHelper = new ClientDnsHelper();
		DomainCache domainCache = new DomainCache();

		echoSocket = new Socket(host, port);
		out = new PrintWriter(echoSocket.getOutputStream(), AUTO_FLUSH);
		in = new BufferedReader(new InputStreamReader(
				echoSocket.getInputStream()));

		clientHelper.welcomeScreen();
		clientHelper.showCursor();

		while ((userInput = stdIn.readLine()) != null) {
			if (clientHelper.isValid(userInput)) {

				if (userInput.equalsIgnoreCase("quit")) {
					break;
				}

				String response = null;
				String cached = domainCache.getDomainByKey(userInput);

				if (cached == null || cached.length() == 0) {
					try{
						
						if(echoSocket == null){
							echoSocket = new Socket(host, port);
							out = new PrintWriter(echoSocket.getOutputStream(), AUTO_FLUSH);
							in = new BufferedReader(new InputStreamReader(
									echoSocket.getInputStream()));
						}
						
						out.println(userInput);
						response = in.readLine();
						String ipAdress = clientHelper
								.getIpAdressFromResponse(response);
						clientHelper.addToCache(userInput, ipAdress, domainCache);
					}catch(Exception e){
						response = "El servidor DNS no esta disponible en este momento";
						echoSocket = null;
						out = null;
						in = null;
					}
					

					
				} else {
					response = "Dominio: " + userInput + " - A - " + cached;
				}

				clientHelper.showResult(response);
			} else {
				clientHelper.showCheckURLErrorInline();
			}

			clientHelper.showCursor();

		}

		closeAll(echoSocket, out, in, stdIn);

	}

	private static void closeAll(Socket echoSocket, PrintWriter out,
			BufferedReader in, BufferedReader stdIn) throws IOException {
		out.close();
		in.close();
		stdIn.close();
		echoSocket.close();
	}

}
